/**
 * 
 */
package com.jm.web.form.baseitem;


import javax.servlet.jsp.JspWriter;

import com.jm.utils.StringBuilderEx;
import com.jm.utils.StringHelper;
import com.jm.utils.rule.BaseRuleEngine;
import com.jm.web.data.BaseDataEntity;
import com.jm.web.data.form.Item;
import com.jm.web.form.support.FormItem;

/**
 * @author yanjie
 *
 * 2011/10/6 上午9:30:46
 */
public class SelectItem extends ListItem{
	@Override
	public void init() {
		super.init();
		this.setNodeName("select");
	}
	
	/**
	 * @param tag
	 */
	public SelectItem() {}
	
	@Override
	public void onRenderSingleBody(JspWriter writer, FormItem item) {
		String optionStyle = this.getBaseTag().GetExtValue("optionStyle", "");
		BaseRuleEngine rule = null;
		BaseDataEntity data = null;
		
		if(!StringHelper.IsNullOrEmpty(optionStyle)){
			rule = new BaseRuleEngine();
			data = new BaseDataEntity();
			rule.init(this.getBaseTag().getPage().getUtils().getForm(), data);
		}
		
		StringBuilderEx sb = new StringBuilderEx();
		boolean btableTagParent = this.getBaseTag().isTableTagParent();
		if(this.getListItems().size() > 0){
			for (int i = 0; i < this.getListItems().size(); i++) {
				Item listItem = this.getListItems().Get(i);
				
				
				
				sb.Append("<option value=\"%1$s\" ",listItem.getValue());
				if(this.getValue().equalsIgnoreCase(listItem.getValue())){
					sb.Append(" selected=\"true\" ");
				}
				if(!StringHelper.IsNullOrEmpty(optionStyle)){
					data.Reset();
					listItem.FilledBaseDataEntity(data);
					rule.setData(data);
					try {
						String tempOptionStyle = String.valueOf(rule.Eval(optionStyle));
						sb.Append(" style=\"%1$s\" ",tempOptionStyle);
					} catch (Exception e) {
						if(i == 0)
							e.printStackTrace();
					}
				}
				sb.Append(" %1$s>%2$s</option>",
						listItem.getExtToString(),
						listItem.getText());
				if(btableTagParent || !this.getBaseTag().isDSP()){
					try {
						writer.write(sb.toString());
					} catch (Exception e) {
						e.printStackTrace();
					}
					sb.Reset();
				}
			}
			
			if(!btableTagParent && this.getBaseTag().isDSP()){
				//将option 的数据 暂时存放到 页面缓存中
				this.getBaseTag().getPage().getSelectData().put(this.getId(),sb.toString());
			}
		} 
		
	}
}
